package org.misty.seckill.interceptor;

import org.jetbrains.annotations.NotNull;
import org.misty.seckill.exception.AuthorizationException;
import org.misty.seckill.redis.SessionKey;
import org.misty.seckill.service.LoginService;
import org.misty.seckill.util.ServletUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Deprecated
public class AuthorizationInterceptor implements HandlerInterceptor {
  public static final Logger logger = LoggerFactory.getLogger(AuthorizationInterceptor.class);

  @Autowired
  private LoginService loginService;

  @Override
  public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, Object handler) {
//    logger.debug("AuthorizationInterceptor.preHandle : " + request.getRequestURI());
    /*var token = ServletUtil.readSessionToken(request);
    var user = loginService.getByToken(token);
    if (user != null) {
      request.setAttribute("user", user);
      loginService.keepAlive(token, user); // 刷新redis
      ServletUtil.writeSessionToken(response, token, SessionKey.TOKEN.getExpiryInSec(), "/");
      return true;
    } else if ("GET".equalsIgnoreCase(request.getMethod()) && !ServletUtil.isAjaxRequest(request)) {
      // 未登录。缓存当前请求路径，用于登录后跳转
      token = loginService.cacheRedirect(token, request.getRequestURI());
      ServletUtil.writeSessionToken(response, token, SessionKey.REDIRECT.getExpiryInSec(), "/");
    }
    throw AuthorizationException.signOut();*/

    // token,user 值由 PreprocessInterceptor 设置
    var token = (String) request.getAttribute("token");
    var user = request.getAttribute("user");
    if (user != null) {
      return true;
    } else if ("GET".equalsIgnoreCase(request.getMethod()) && !ServletUtil.isAjaxRequest(request)) {
      // 未登录。缓存当前请求路径，用于登录后跳转
      token = loginService.cacheRedirect(token, request.getRequestURI());
      ServletUtil.writeSessionToken(response, token, SessionKey.REDIRECT.getExpiryInSec(), "/");
    }
    throw AuthorizationException.signOut();
  }
}
